package com.mrs.service.impl;

import com.mrs.common.ResponseResult;
import com.mrs.common.vo.BlogUserLoginVo;
import com.mrs.common.vo.UserInfoVo;
import com.mrs.entity.LoginUser;
import com.mrs.entity.User;
import com.mrs.service.BlogLoginService;
import com.mrs.utils.BeanCopyUtils;
import com.mrs.utils.JwtUtil;

import com.mrs.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * description: BlogLoginServiceImpl
 * date: 2022/8/7 22:06
 * author: MR.孙
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //因为AuthenticationManager会通过UserDetailsService去比对用户密码,UserDetailsService比对完后会
        //AuthenticationManager.authenticate会有一个返回值,里面封装了UserDetails等信息
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判断是否通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //获取userId,生成token
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把用户信息存入到redis中
        redisCache.setCacheObject("bloglogin:"+userId,loginUser);


        //把token和userInfo封装返回
        UserInfoVo userInfo = BeanCopyUtils.copyBean(loginUser.getUser(),UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, userInfo);

        return ResponseResult.okResult(blogUserLoginVo);
    }

    @Override
    public ResponseResult logout() {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getUser().getId();

        //删除redis中的用户信息
        redisCache.deleteObject("bloglogin:"+userId);

        return ResponseResult.okResult();
    }
}
